package com.jied.duodian.config;

import com.jied.duodian.service.Impl.JwtUserDetailsServiceImpl;
import com.jied.duodian.util.handler.EntryPointUnauthorizedHandler;
import com.jied.duodian.util.handler.JwtAuthenticationTokenFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.BeanIds;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * Description:
 *
 * @author LiJie
 * @date Created on 2020/10/30
 * WWW https://github.com/j6l
 */

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtUserDetailsServiceImpl userDetailsService;
    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
    @Autowired
    private EntryPointUnauthorizedHandler entryPointUnauthorizedHandler;


    @Autowired
    public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        authenticationManagerBuilder.userDetailsService( userDetailsService ).passwordEncoder( passwordEncoder() );
    }

    private PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.addFilterBefore( jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class );

        //关闭scrf   关闭session管理器
        http.csrf().disable().sessionManagement().sessionCreationPolicy( SessionCreationPolicy.STATELESS );

        http.authorizeRequests()
                .antMatchers(
                        HttpMethod.GET,
                        "/",
                        "/*.html",
                        "/favicon.ico",
                        "/img/*.jpg",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js"
                ).permitAll()
                // .antMatchers( HttpMethod.OPTIONS, "/**" ).permitAll()
                .antMatchers( "/auth/**" ).permitAll()
                .antMatchers( "/product/all" ).permitAll()
                .antMatchers( "/lei/get" ).permitAll()
                .antMatchers( "/auth/auth" ).permitAll()
                .antMatchers( "/file/fileUpload" ).permitAll()
                // 角色校验时，会自动拼接 "ROLE_"
                // .antMatchers( "/user/**" ).hasAnyRole( "ADMIN", "USER" )
                .anyRequest().authenticated();   // 任何请求,登录后可以访问

        // 禁用缓存
        http.headers().cacheControl();
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource configurationSource = new UrlBasedCorsConfigurationSource();
        CorsConfiguration cors = new CorsConfiguration();
        cors.setAllowCredentials( true );
        cors.addAllowedOrigin( "*" );
        cors.addAllowedHeader( "*" );
        cors.addAllowedMethod( "*" );
        configurationSource.registerCorsConfiguration( "/**", cors );
        return new CorsFilter( configurationSource );
    }


    @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}
